package com.tanhua.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.dubbo.mongo.VideoAPI;
import com.tanhua.exception.MyException;
import com.tanhua.interceptor.UserHolder;
import com.tanhua.mongo.Video;
import com.tanhua.vo.ErrorResult;
import com.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class SmallVideoService {

    //调用fastdfs
    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @DubboReference
    private VideoAPI videoAPI;

    public void publishVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws Exception {
        //0 不能为空
        if (videoThumbnail.isEmpty()||videoFile.isEmpty()){
            throw new MyException(ErrorResult.codeError());
        }
        //1 上传图片
        String filename = videoThumbnail.getOriginalFilename().substring(videoThumbnail.getOriginalFilename().lastIndexOf(".") + 1);
        StorePath imgStorePath = client.uploadFile(videoThumbnail.getInputStream(), videoThumbnail.getSize(), filename, null);
        String imgPath = webServer.getWebServerUrl()+imgStorePath.getFullPath();
        //2 上传视频
        String videoname = videoFile.getOriginalFilename().substring(videoFile.getOriginalFilename().lastIndexOf(".") + 1);
        StorePath videoFilePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), videoname, null);
        String videoPath = webServer.getWebServerUrl()+videoFilePath.getFullPath();
        //3 调用mongo--构建video
        Video video = new Video();
        video.setId(ObjectId.get());
        video.setVid(stringRedisTemplate.opsForValue().increment("VIDEO_VID"));
        video.setCreated(System.currentTimeMillis());
        video.setUserId(UserHolder.getUserId());
        video.setText("我就是我，不一样的烟火");
        video.setPicUrl(imgPath);
        video.setVideoUrl(videoPath);

        videoAPI.save(video);
    }

    /**
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult videoList(Integer page, Integer pagesize) {
        //1 去redis中查找：VIDEOS_RECOMMEND_UserID
        String value = stringRedisTemplate.opsForValue().get("VIDEOS_RECOMMEND_"+UserHolder.getUserId());

        //


        return null;
    }
}
